<?php
namespace EM\NewsBundle\Services;

use Doctrine\ORM\EntityManager;
use EM\NewsBundle\Entity\Geography;
/*Las configuraciones de este archivo se pueden encontrar 
 * en Resources/config/services.yml */
class UtilsService extends \Twig_Extension
{
  /**
     *
     * @var EntityManager 
     */
    protected $em; //entity manager variable
    
    
    /** Con esta funcion, se inyecta 
     * el valor del entity manager ***/
    
    public function __construct(EntityManager $entityManager)
    {
       // var_dump($entityManager);
        //exit(); // I've never saw it happen, looks like constructor never called
        $this->em = $entityManager;
    }
    
    
    /**Con esta funcion se construye el filtro en Twig **/
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('authors', array($this, 'findAuthorAction')),
            new \Twig_SimpleFilter('emlang', array($this, 'findLanguagesAction')),
            new \Twig_SimpleFilter('listLang', array($this, 'findLangLinkedAction')),
            new \Twig_SimpleFilter('countriesbyauthor', array($this, 'findCountriesByAuthorAction')),
            new \Twig_SimpleFilter('langcountriesandauthor', array($this, 'findLanguagesByAuthorAndCountryAction')),
            new \Twig_SimpleFilter('status', array($this, 'filterNewsByStatusAction')),
        );
    }
    
    /**
     * Esta es la funcion que se encarga 
     * de tomar los datos del autor (Concretamente el username) 
     * ya sea para ser ocupado en un template o en un controlador.**/
    
    public function findAuthorAction($id){
        $em=$this->em;
        $users=$em->getRepository('EMNewsBundle:Users')->find($id);
        return $users;
    }
    public function filterNewsByStatusAction($news,$status){
        $counter=0;
        foreach($news as $new){
            if($new->getstatus()==$status){
                $counter++;
              }
            
        }
        return $counter;
    }
    
   

   public function findLangLinkedAction($countryId){
       $em=$this->em;
       $langs=$em->getRepository('EMNewsBundle:GeoLangRelation')->findByGeo($countryId);
       foreach($langs as $lang){
           echo $lang->getLang()->getName()."<br>";
           
       }
       
       
   }
   public function createListLangAction($languages){         
       $langList="";   
       $last_item = end($languages);
         foreach($languages as $lang){
          
           $lng= $this->findLanguagesAction($lang->getLang());
           if ($lang == $last_item) {
            $langList.=$lng.".";
           }
           else
           {
            $langList.=$lng.", ";   
           }
       }
       return $langList;
   }
   public function findCountriesByAuthorAction($author){
        $em=$this->em;
        //$em = $this->getDoctrine()->getManager();
        $query = $em->createQuery(
            'SELECT g.id, g.name FROM EMNewsBundle:Geography g, EMNewsBundle:UserGeoLangSettings s, EMNewsBundle:GeoLangRelation r WHERE s.user=:id and g.id=r.geo and s.geoLang=r.id group by g.id order by g.name asc')
                ->setParameter('id', $author);

        $aux = $query->getResult();
        $countries=new Geography();
        $countries =$aux;
//        foreach($aux as  $i => $a){ 
//           $countries->setName($a['name']);
//           
//        //   $languages[$i]= $a['name'];
//            
//        }
      // $languages=$em->getRepository('EMNewsBundle:UserGeoLangSettings')->findBy(array('user' => $author));
     //  print_r($countries);
    //  exit();
       return $countries;
   }
   /**
     * Get languages
     *
     * @return \EM\NewsBundle\Entity\Languages 
     */
   public function findLanguagesByAuthorAndCountryAction($countryid,$author){
        $em=$this->em;
        //$em = $this->getDoctrine()->getManager();
        $query = $em->createQuery(
            'SELECT l.id, l.name 
             FROM EMNewsBundle:Languages l, EMNewsBundle:UserGeoLangSettings s, EMNewsBundle:GeoLangRelation r 
             WHERE r.geo=:countryid and s.user=:author and l.id=r.lang and s.geoLang=r.id 
             order by l.name asc')
            ->setParameters(array(
                                'countryid' => $countryid,
                                'author' => $author,
                            ));

        $languages = $query->getResult();
      // $languages=$em->getRepository('EMNewsBundle:UserGeoLangSettings')->findBy(array('user' => $author));
       
       return $languages;
   }
   
    public function getName()
    {
        return 'em_extension';
    }
}